<?php

namespace app\admin\controller;

use app\admin\controller\swoole\MiniCusMsgTask;
use app\admin\controller\swoole\Platform;
use app\admin\model\Authorizer;
use app\admin\model\BeanstalkTask;
use app\admin\model\Category;
use app\admin\model\CustomerMessage;
use Pheanstalk\Pheanstalk;
use think\facade\Env;
use think\swoole\facade\Task;

class Customer extends Base
{
    // 客服信息界面首页
    public function index()
    {
        return $this->fetch('customer/index');
    }

    // 获取客服消息列表
    public function get_customer_msg_list()
    {
        $page = $this->request->post('page', 1);
        $pagesize = $this->request->post('pagesize', 10);
        $keyword = $this->request->post('keyword');
        $data['list'] = CustomerMessage::whereLike('remark', '%' . $keyword . '%')
            ->where('delstatus', 1)
            ->limit(($page - 1) * $pagesize, $pagesize)
            ->order('id', 'desc')
            ->select();
        $data['total'] = CustomerMessage::whereLike('remark', '%' . $keyword . '%')
            ->where('delstatus', 1)
            ->count();
        return $this->api_result('', $data);
    }

    // 删除客服消息
    public function del_msg()
    {
        $msgid = $this->request->param('msgid');
        $msg = CustomerMessage::get($msgid);
        $msg->delstatus = 0;
        return $msg->save();
    }

    // 批量删除客服消息
    public function del_msg_list()
    {
        $id_list = $this->request->post('id_list');
        $count = 0;
        // 遍历处理任务
        foreach ($id_list as $id) {
            $msg = CustomerMessage::get($id);
            if ($msg) {
                $msg->delstatus = 0;
                if ($msg->save()) {
                    $count++;
                }
            }
        }
        return $count;
    }

    // 添加客服消息界面
    public function handle_msg_view()
    {
        $msgid = $this->request->param('msgid');
        $this->assign('msgid', $msgid);
        return $this->fetch('customer/handle_msg');
    }

    //上传小程序卡片图
    public function upload_img()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = $this->request->file('file');
        // 移动到框架应用根目录/uploads/ 目录下
        $rootpath = Env::get('root_path');
        $info = $file->move($rootpath . 'public/static/uploads');
        if ($info) {
            // 成功上传后 获取上传信息
            $files = 'http://wechat.nanxuncn.cn/static/uploads/' . $info->getSaveName();
            return $files;
        } else {
            // 上传失败获取错误信息
            return $file->getError();
        }
    }

    // 处理客服信息(新增或修改)
    public function do_handle_msg()
    {
        $msgid = $this->request->param('msgid');
        $msg = $this->request->param('msg');

        $cus_msg = CustomerMessage::get($msgid);
        if (!$cus_msg) {
            $cus_msg = new CustomerMessage();
        }
        $cus_msg->remark = $msg['remark'];
        $cus_msg->type = $msg['type'];
        $cus_msg->createtime = date('Y-m-d H:i:s', time());
        $cus_msg->delstatus = 1;

        switch ($msg['type']) {
            case 'text':
                $cus_msg->content = $msg['content'];
                break;
            case 'news':
                $cus_msg->title = $msg['title'];
                $cus_msg->desc = $msg['desc'];
                $cus_msg->image = $msg['image'];
                $cus_msg->url = $msg['url'];
                break;
            case 'mini':
                $cus_msg->title = $msg['title'];
                $cus_msg->xcx_appid = $msg['xcx_appid'];
                $cus_msg->xcx_pagepath = $msg['xcx_pagepath'];
                $cus_msg->xcx_image_url = $msg['xcx_image_url'];
                break;
        }

        return $cus_msg->save();
    }

    // 获取当前客服信息
    public function get_msg()
    {
        $msgid = $this->request->param('msgid');
        return CustomerMessage::get($msgid);
    }

    // 获取当前客服消息下绑定的账号界面
    public function account_info_view()
    {
        $msgid = $this->request->param('msgid');
        $this->assign('msgid', $msgid);
        return $this->fetch('customer/account_info');
    }

    // 获取当前客服消息下绑定的账号
    public function get_account_list()
    {
        $page = $this->request->post('page', 1);
        $pagesize = $this->request->post('pagesize', 10);
        $keyword = $this->request->post('keyword');
        $msgid = $this->request->post('msgid');
        $gh_list = CustomerMessage::where('id', $msgid)->value('gh_list');
        $authorizer_list = Authorizer::whereIn('ghid', $gh_list)
            ->whereLike('name|ghid', '%' . $keyword . '%')
            ->where('delstatus', 1)
            ->limit(($page - 1) * $pagesize, $pagesize)
            ->order('id', 'desc')
            ->select();
        $total = Authorizer::whereIn('ghid', $gh_list)
            ->whereLike('name|ghid', '%' . $keyword . '%')
            ->where('delstatus', 1)
            ->count();
        foreach ($authorizer_list as $auth) {
            $auth->category = Category::where('id', $auth->category)->value('categoryname');
            $auth->category2 = Category::where('id', $auth->category2)->value('categoryname');
        }
        $data['list'] = $authorizer_list;
        $data['total'] = $total;
        return $this->api_result('', $data);
    }

    // 添加账号界面
    public function add_account_view()
    {
        $categorys = Category::all(['delstatus' => 1, 'level' => 1]);
        $msgid = $this->request->param('msgid');
        $msg_type = CustomerMessage::where('id', $msgid)->value('type');
        $this->assign('msgid', $msgid);
        $this->assign('msg_type', $msg_type);
        $this->assign('categorys', $categorys);
        return $this->fetch('customer/add_account');
    }

    //获取分类列表
    public function get_category()
    {
        $pid = $this->request->post('pid', 0);
        $catregory = Category::where(['delstatus' => 1, 'pid' => $pid])->select();
        return $catregory;
    }

    // 获取消息未绑定的公众号
    public function get_account_list_without_msg()
    {
        $page = $this->request->post('page', 1);
        $pagesize = $this->request->post('pagesize', 10);
        $msgid = $this->request->post('msgid');
        $keyword = $this->request->post('keyword');
        $category = $this->request->post('category', '');
        $category2 = $this->request->post('category2', '');
        if ($category !== '') {
            $map[] = ['category', '=', $category];
        }
        if ($category2 !== '') {
            $map[] = ['category2', '=', $category2];
        }
        $map[] = ['delstatus', '=', 1];
        $gh_list = CustomerMessage::where('id', $msgid)->value('gh_list');
        $list = Authorizer::whereNotIn('ghid', $gh_list)
            ->whereLike('name|ghid', '%' . $keyword . '%')
            ->where($map)
            ->limit(($page - 1) * $pagesize, $pagesize)
            ->order('id', 'desc')
            ->select();
        $total = Authorizer::whereNotIn('ghid', $gh_list)
            ->whereLike('name|ghid', '%' . $keyword . '%')
            ->where($map)
            ->count();
        foreach ($list as $v) {
            $v->category = Category::where('id', $v->category)->value('categoryname');
            $v->category2 = Category::where('id', $v->category2)->value('categoryname');
        }
        $data = ['list' => $list, 'total' => $total];
        return $this->api_result('', $data);
    }

    // 根据分类绑定公众号
    public function add_acc_by_category()
    {
        // 消息id
        $msgid = $this->request->post('msgid');
        $ghids = $this->request->post('ghids');
        $right_list = array();
        // 得到需要添加的公众号列表
        foreach ($ghids as $ghid) {
            $ghid = trim(trim($ghid), ',');
            $gh = Authorizer::get(['ghid' => $ghid]);
            if ($gh) {
                array_push($right_list, $ghid);
            }
        }
        if (count($right_list)) {
            return $this->do_add_acc($right_list, $msgid);
        } else {
            return false;
        }
    }

    // 根据传入的原始id列表字符串绑定公众号
    public function add_acc_list()
    {
        // 消息id
        $msgid = $this->request->post('msgid');
        // 获取并处理字符串
        $ghids = trim(trim($this->request->post('ghids')), ',');
        $ghid_list = explode(',', $ghids);
        $right_list = array();
        // 得到需要添加的公众号列表
        foreach ($ghid_list as $ghid) {
            $ghid = trim(trim($ghid), ',');
            $gh = Authorizer::get(['ghid' => $ghid]);
            if ($gh) {
                array_push($right_list, $ghid);
            }
        }
        if (count($right_list)) {
            return $this->do_add_acc($right_list, $msgid);
        } else {
            return false;
        }
    }

    // 添加绑定公众号逻辑
    public function do_add_acc($right_list, $msgid)
    {
        $count = count($right_list);
        // 拿到已经绑定的公众号列表
        $msg = CustomerMessage::get($msgid);
        $old_list = explode(',', $msg->gh_list);

        // 得到新添加的
        $new_list = array_diff($right_list, $old_list);
        if (count($new_list)) {
            foreach ($new_list as $ghid) {
                if ($msg->gh_list) {
                    $msg->gh_list .= ',' . $ghid;
                } else {
                    $msg->gh_list .= $ghid;
                }
            }
            if ($msg->save()) {
                return $count;
            } else {
                return false;
            }
        } else {
            return $count;
        }
    }

    // 根据分类绑定公众号(异步)
    public function add_acc_by_category_async()
    {
        // 消息id
        $msgid = $this->request->post('msgid');
        $ghids = $this->request->post('ghids');
        $right_list = array();
        // 得到需要添加的公众号列表
        foreach ($ghids as $ghid) {
            $ghid = trim(trim($ghid), ',');
            $gh = Authorizer::get(['ghid' => $ghid]);
            if ($gh) {
                array_push($right_list, $ghid);
            }
        }
        if (count($right_list)) {
            return $this->do_add_acc_async($right_list, $msgid);
        } else {
            return false;
        }
    }

    // 根据传入的原始id列表字符串绑定公众号(异步)
    public function add_acc_list_async()
    {
        // 消息id
        $msgid = $this->request->post('msgid');
        // 获取并处理字符串
        $ghids = trim(trim($this->request->post('ghids')), ',');
        $ghid_list = explode(',', $ghids);
        $right_list = array();
        // 得到需要添加的公众号列表
        foreach ($ghid_list as $ghid) {
            $ghid = trim(trim($ghid), ',');
            $gh = Authorizer::get(['ghid' => $ghid]);
            if ($gh) {
                array_push($right_list, $ghid);
            }
        }
        if (count($right_list)) {
            return $this->do_add_acc_async($right_list, $msgid);
        } else {
            return false;
        }
    }

    // 添加绑定公众号逻辑(异步)
    public function do_add_acc_async($right_list, $msgid)
    {
        $platform = new Platform();
        $count = count($right_list);
        // 拿到已经绑定的公众号列表
        $msg = CustomerMessage::get($msgid);
        $old_list = explode(',', $msg->gh_list);

        // 得到新添加的
        $new_list = array_diff($right_list, $old_list);
        if (count($new_list)) {
            foreach ($new_list as $ghid) {
                $token = $platform->getGhTokenWithGhid($ghid);
                $task = new MiniCusMsgTask($ghid, $token, $msgid);
                Task::async($task);
                if ($msg->gh_list) {
                    $msg->gh_list .= ',' . $ghid;
                } else {
                    $msg->gh_list .= $ghid;
                }
            }
            $msg->save();
        }
        return $count;
    }

    //  删除绑定公众号逻辑
    public function do_del_account()
    {
        $ghids = $this->request->post('ghids');
        $msgid = $this->request->post('msgid');

        $msg = CustomerMessage::get($msgid);

        $gh_list = explode(',', $msg->gh_list);
        // 存在就删除
        $new_list = array_diff($gh_list, $ghids);
        $msg->gh_list = '';
        $count = count($new_list);
        if ($count) {
            foreach ($new_list as $ghid) {
                if ($msg->gh_list) {
                    $msg->gh_list .= ',' . $ghid;
                } else {
                    $msg->gh_list .= $ghid;
                }
            }
            return $msg->save();
        } else {
            return false;
        }
    }

    // 清空绑定公众号
    public function do_clear_account()
    {
        $msgid = $this->request->post('msgid');
        $msg = CustomerMessage::get($msgid);
        $msg->gh_list = '';
        return $msg->save();
    }

    // 发送消息界面
    public function send_msg_view()
    {
        $msgid = $this->request->param('msgid');
        $this->assign('msgid', $msgid);
        return $this->fetch('customer/send_msg');
    }

    // 发送任务列表界面
    public function task_view()
    {
        return $this->fetch('customer/task_list');
    }

    // 获取发送任务列表
    public function get_task_list()
    {
        $page = $this->request->post('page', 1);
        $pagesize = $this->request->post('pagesize', 10);
        $keyword = $this->request->post('keyword');
        $msg_list = CustomerMessage::whereLike('remark', '%' . $keyword . '%')
            ->where('delstatus', 1)
            ->limit(($page - 1) * $pagesize, $pagesize)
            ->order('id', 'desc')
            ->select();
        $task_list = array();

        foreach ($msg_list as $msg) {
            $tasks = BeanstalkTask::where('msg_id', $msg->id)->where('delay', '>', time())->select();
            if ($tasks) {
                foreach ($tasks as $task) {
                    $task->msg = $msg->remark;
                    $task->delay = date("Y-m-d H:i:s", $task->delay);
                    array_push($task_list, $task);
                }
            }
        }
        return $task_list;
    }

    // 删除发送任务
    public function del_task()
    {
        $pheanstalk = new Pheanstalk('127.0.0.1');
        $id = $this->request->post('id');
        $task = BeanstalkTask::get($id);
        $job_list = explode(',', $task->job_list);
        foreach ($job_list as $id) {
            $job = $pheanstalk->peek($id);
            if ($job) {
                $pheanstalk->delete($job);
            }
        }
        $res = $task->delete();
        if ($res !== false) {
            return true;
        } else {
            return false;
        }
    }
}
